import * as utils from '../utils'

function createCourse17 (gl: WebGLRenderingContext) {
  gl.clearColor(0.0, 0.0, 0.0, 1.0)
  gl.clear(gl.COLOR_BUFFER_BIT)

  const vectexShaderSrc = `
  attribute vec4 a_Position;
  attribute vec2 a_UV;
  varying vec2 v_UV;
    void main() {
        gl_Position = a_Position;
        v_UV = a_UV;
    }
  `

  const fragmentShaderSrc = `
    precision mediump float;
    uniform sampler2D u_Sampler0;
    uniform sampler2D u_Sampler1;
    varying vec2 v_UV;
      void main() {
          vec4 color0 = texture2D(u_Sampler0, v_UV);
          vec4 color1 = texture2D(u_Sampler1, v_UV);
          gl_FragColor = color0 * color1;
      }
    `

  const program = utils.initShaders(gl, vectexShaderSrc, fragmentShaderSrc)

  const vertices = new Float32Array([
    -0.5, 0.5, 0.0, 1.0,
    -0.5, -0.5, 0.0, 0.0,
    0.5, 0.5, 1.0, 1.0,
    0.5, -0.5, 1.0, 0
  ])
  const aPosition = gl.getAttribLocation(program, 'a_Position')
  const aUV = gl.getAttribLocation(program, 'a_UV')

  const vectexBuffer = gl.createBuffer()
  gl.bindBuffer(gl.ARRAY_BUFFER, vectexBuffer)
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)

  const FSIZE = vertices.BYTES_PER_ELEMENT
  gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, FSIZE * 4, 0)
  gl.enableVertexAttribArray(aPosition)

  gl.vertexAttribPointer(aUV, 2, gl.FLOAT, false, FSIZE * 4, FSIZE * 2)
  gl.enableVertexAttribArray(aUV)

  const uSampler0 = gl.getUniformLocation(program, 'u_Sampler0')
  const uSampler1 = gl.getUniformLocation(program, 'u_Sampler1')

  const src0 = 'https://vue-three.oss-cn-shanghai.aliyuncs.com/images/redflower.jpg'
  const src1 = 'https://vue-three.oss-cn-shanghai.aliyuncs.com/images/circle.gif'
  Promise.all([loadImage(src0), loadImage(src1)]).then((data) => {
    data.forEach((image, index) => {
      createTexture(index, image)
    })
    gl.clear(gl.COLOR_BUFFER_BIT)
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
  })

  function loadImage (url: string): Promise<HTMLImageElement> {
    return new Promise(resolve => {
      const image = new Image()
      image.src = url
      image.crossOrigin = ''
      image.onload = function () {
        resolve(image)
      }
    })
  }

  function createTexture (index: number, image: HTMLImageElement) {
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1)
    const texture = gl.createTexture()
    if (index === 0) {
      gl.activeTexture(gl.TEXTURE0)
    } else {
      gl.activeTexture(gl.TEXTURE1)
    }
    gl.bindTexture(gl.TEXTURE_2D, texture)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image)
    if (index === 0) {
      gl.uniform1i(uSampler0, 0)
    } else {
      gl.uniform1i(uSampler1, 1)
    }
    return texture
  }
}

export {
  createCourse17
}
